<template>
  <div class="login-container">
    <div class="login-form">
      <h2>里欧12306售票系统</h2>
      <a-form :model="formState" auto-complete="off" @finish="handleLogin">
        <a-form-item name="mobile" :rules="[{ required: true, message: '请输入手机号!' }]">
          <a-input v-model:value="formState.mobile" placeholder="请输入手机号">
            <template #prefix>
              <MobileOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="code" :rules="[{ required: true, message: '请输入验证码!' }]">
          <a-input-group v-if="!diaabledTime" compact>
            <a-input
              v-model:value="formState.code"
              style="width: calc(100% - 110px)"
              placeholder="请输入验证码"
            ></a-input>
            <a-button v-if="!diaabledTime" type="primary" @click="sendCode">获取验证码</a-button>
          </a-input-group>
          <a-input-group v-if="diaabledTime" compact>
            <a-input
              v-model:value="formState.code"
              style="width: calc(100% - 130px)"
              placeholder="请输入验证码"
            ></a-input>
            <a-button type="primary" disabled>{{ time }}秒后重新获取</a-button>
          </a-input-group>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading" block>登录</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div>
      <a-modal v-model:open="open" title="图形校验" class="photoModal" @ok="handleOk">
        <a-input-group compact>
          <a-input
            v-model:value="formState.photoCode"
            style="width: calc(100% - 110px)"
            placeholder="请输入图形验证码"
          ></a-input>
          <img :src="`data:image/png;base64,${imgCode}`" class="photoCode" @click="getPhotoCode" />
        </a-input-group>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { MobileOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { loginApi } from '@/api/login';
import { setToken } from '@/utils/auth';

interface FormState {
  mobile: string;
  code: string;
  photoCode?: string;
}

const router = useRouter();
const loading = ref(false);
const isPhoto = ref(false);
const diaabledTime = ref(false);
const time = ref(30);
const timer = ref<any>(null);

const formState = reactive<FormState>({
  mobile: '13800000000',
  code: '',
  photoCode: '',
});
onMounted(() => {
  if (localStorage.getItem('photoCodeTime')) {
    time.value = Number(localStorage.getItem('photoCodeTime'));
    timer.value = setInterval(() => {
      if (time.value > 1 && diaabledTime.value) {
        time.value--;
        localStorage.setItem('photoCodeTime', time.value.toString());
      } else {
        time.value = 30;
        localStorage.removeItem('photoCodeTime');
        diaabledTime.value = false;
      }
    }, 1000);
    diaabledTime.value = true;
  }
});

const sendCode = async (): Promise<void> => {
  try {
    if (localStorage.getItem('photoCode') == '1') {
      // 调用后端获取图片验证码
      await getPhotoCode();
      showPhotoModal();
    } else {
      const { data } = await loginApi.sendCode(formState.mobile);
      diaabledTime.value = true;
      console.log('data', data);
      message.success(`验证码为：${data.code}`);
      clearInterval(timer.value);
      timer.value = setInterval(() => {
        if (time.value > 1 && diaabledTime.value) {
          time.value--;
          localStorage.setItem('photoCodeTime', time.value.toString());
        } else {
          time.value = 10;
          localStorage.removeItem('photoCodeTime');
          diaabledTime.value = false;
        }
      }, 1000);
    }
  } catch (error: any) {
    message.error(error.message);
  }
};
const imgCode = ref('');
const open = ref<boolean>(false);

const showPhotoModal = (): void => {
  open.value = true;
};

const handleOk = async (e: MouseEvent): Promise<void> => {
  try {
    await loginApi.judgePhotoCode(formState.mobile, formState.photoCode!);
    localStorage.removeItem('photoCode');
    sendCode();
    console.log(e);
    open.value = false;
  } catch (error) {
    getPhotoCode();
    console.log('error', error);
  }
};
const handleLogin = async (): Promise<void> => {
  try {
    loading.value = true;
    const { data } = await loginApi.login(formState.mobile, formState.code);
    console.log('data', data);
    setToken(data.token, true);
    localStorage.setItem(
      'userInfo',
      JSON.stringify({
        id: data.id,
        mobile: data.mobile,
      })
    );
    // 模拟登录验证
    setTimeout(() => {
      loading.value = false;
      // 登录成功后跳转到首页
      router.push({ path: '/' });
      message.success('登录成功');
    }, 1000);
  } catch (error) {
    localStorage.setItem('photoCode', '1');
    console.log('error', error);
  } finally {
    loading.value = false;
  }
};
const getPhotoCode = async (): Promise<void> => {
  try {
    const { data } = await loginApi.getPhotoCode(formState.mobile);
    imgCode.value = data.img;
    isPhoto.value = true;
    localStorage.setItem('photoCode', '1');
    console.log('data', data);
  } catch (error) {
    console.log('error', error);
  }
};
</script>

<style scoped lang="less">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-form {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.login-form h2 {
  text-align: center;
  margin-bottom: 24px;
}
.photoCode {
  width: 100px;
  height: 40px;
}
.photoModal :global(.ant-modal-footer) {
  display: flex;
  justify-content: center;
  text-align: center;
}
</style>
